package com.laizhenghua.share.device.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laizhenghua.share.device.domain.entity.Cabinet;
import com.laizhenghua.share.device.mapper.CabinetMapper;
import com.laizhenghua.share.device.service.ICabinetService;
import com.laizhenghua.share.system.api.model.LoginUser;
import com.share.common.security.utils.SecurityUtils;
import lombok.extern.java.Log;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * TODO
 *
 * @Description
 * @Author laizhenghua
 * @Date 2025/6/29 08:44
 **/
@Log
@Service
public class ICabinetServiceImpl extends ServiceImpl<CabinetMapper, Cabinet> implements ICabinetService {

    private final CabinetMapper cabinetMapper;

    public ICabinetServiceImpl(CabinetMapper cabinetMapper) {
        this.cabinetMapper = cabinetMapper;
    }

    @Override
    public List<Cabinet> searchPageList(Cabinet cabinet) {
        return cabinetMapper.searchPageList(cabinet);
    }

    @Override
    public Cabinet customSave(Cabinet cabinet) {
        if (ObjectUtil.isNull(cabinet.getCreateTime())) {
            cabinet.setCreateTime(new Date());
        }
        if (ObjectUtil.isNull(cabinet.getCreateBy())) {
            LoginUser user = SecurityUtils.getLoginUser();
            if (ObjectUtil.isNotNull(user)) {
                cabinet.setCreateBy(user.getUsername());
            }
        }
        // 更新
        if (ObjectUtil.isNotNull(cabinet.getId())) {
            cabinet.setUpdateTime(new Date());
            LoginUser user = SecurityUtils.getLoginUser();
            if (ObjectUtil.isNotNull(user)) {
                cabinet.setUpdateBy(user.getUsername());
            }
        }
        boolean s = this.saveOrUpdate(cabinet);
        if (s) {
            return this.getById(cabinet.getId());
        }
        return null;
    }

    @Override
    public List<Cabinet> searchNoUse(String keyword) {
        LambdaQueryWrapper<Cabinet> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Cabinet::getName, keyword);
        wrapper.eq(Cabinet::getDelFlag, "0");
        wrapper.eq(Cabinet::getStatus, "0");
        return cabinetMapper.selectList(wrapper);
    }

    @Override
    public Cabinet getCabinetByNo(String cabinetNo) {
        LambdaQueryWrapper<Cabinet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cabinet::getCabinetNo, cabinetNo);
        return cabinetMapper.selectOne(wrapper);
    }
}
